package cn.itzzx.lagou.datasource;

import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;


/**
 * TODO
 *
 * @author Martin
 * @since 1.0
 */
@Component
public class JdbcTemplateFactory extends AbstractFactoryBean<JdbcTemplate> {

    private static JdbcTemplate jdbcTemplate;

    public JdbcTemplateFactory() {
        setSingleton(false);
    }

    @Override
    public Class<?> getObjectType() {
        return JdbcTemplate.class;
    }

    @Override
    protected JdbcTemplate createInstance() throws Exception {
        if (jdbcTemplate == null) {
            jdbcTemplate = new JdbcTemplate();
            final DataSource dataSource = DataSourceHandler.getDruidDataSource();
            jdbcTemplate.setDataSource(dataSource);
        }
        return jdbcTemplate;
    }

    /**
     * 监听到zk新的连接后，将jdbcTemplate重新配置数据源
     */
    public static void jdbcTemplateSwitchSource() {
        if (jdbcTemplate != null) {
            final DataSource dataSource = DataSourceHandler.getDruidDataSource();
            jdbcTemplate.setDataSource(dataSource);
        }
    }
}
